import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # 图示<img src="https://pytorch.org/tutorials/_images/mnist.png"/>
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)  # 输入通道数，输出通道数，卷积核大小
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)  # 5*5 from image dimension
        self.fc2 = nn.Linear(120, 84)  # 120是输入，84是输出
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 只需要定义forward函数，就可以使用autograd为您自动定义backward函数（计算梯度）。
        # 您可以在forward函数中使用任何张量操作。
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square, you can specify with a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = torch.flatten(x, 1)  # flatten all dimensions except the batch dimension
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()
print(net)

# 模型的可学习参数由net.parameters()返回
params = list(net.parameters())
print("len(params) = ", len(params))
print("params[0].size() = ", params[0].size())  # conv1's .weight

# 尝试一个32x32随机输入
input = torch.randn(1, 1, 32, 32)
output = net(input)
print("output = ", output)


target = torch.randn(10)  # a dummy target, for example
target = target.view(1, -1)  # make it the same shape as output
criterion = nn.MSELoss()  # 均方误差计算损失

loss = criterion(output, target)
print("loss = ", loss)
print(loss.grad_fn)  # MSELoss
print(loss.grad_fn.next_functions[0][0])  # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])  # ReLU


# 反向传播 与 更新权重
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)

# in your training loop:
# 需要清除现有的梯度，否则梯度将累积到现有的梯度中。
optimizer.zero_grad()   # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()    # Does the update
